#include <iostream>
#include <string>
using std::ios;
using std::string;
using std::cout;
using std::endl;

#ifdef __cplusplus
extern "C"{
#endif
#include "cmd2argv.h"
#include "fork_and_exec.h"
// C code...
#include <sys/types.h>
#include <unistd.h>

#ifdef __cplusplus
}
#endif
#define LOG_ERROR(fmt, ...) printf("%s(%d) %s(): " fmt "\n", __FILE__, __LINE__,\
                                    __FUNCTION__, ## __VA_ARGS__)

#define MAX_CMD_LEN         0x100
//#define MAX_ARGV_STR_LEN    0x100
#define MAX_ARGV_LEN        0x80



#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif

int exec_with_args(const char *str_cmd_with_argvs, int wait_pid)
{
    string tmp_str;
    char* argv[MAX_ARGV_LEN];
    char buf[MAX_CMD_LEN];
    size_t buf_len = sizeof(buf);
    size_t argv_len = MAX_ARGV_LEN;

    tmp_str = ". " + string(str_cmd_with_argvs);

    C2A_RESULT res = cmd2argv(tmp_str.c_str(), buf, &buf_len, &argv[0], &argv_len, NULL);
    if (res != C2A_OK)
    {
        LOG_ERROR("cmd2argv() failed.");
        return 0;
    }
    return do_exec_with_args(argv, wait_pid);
}


int main(int argc, char * argv[])
{
    char cmd[] = "pwd"; // 不能支持带有';'的命令
    //char cmd[] = "pwd; ls -al"; // 不能支持带有';'的命令

    if(argc == 1)
    {
        exec_with_args(cmd, 0);
    } else
    {
        exec_with_args(argv[1], 0);
    }

    return 0;
}
